from PyQt4 import QtCore
from PyQt4 import QtGui
from ctypes import c_bool, c_int, WINFUNCTYPE, windll
from ctypes.wintypes import UINT
import sys

import config
from about import AboutDialog

DEBUG = False

def debug_out(str):
    if DEBUG:
        print(str)
    else:
        pass
    
# Win32 API prototype
#BOOL RegisterHotKey(      
#    HWND hWnd,
#   int id,
#   UINT fsModifiers,
#   UINT vk
#);

# come from WinUser.h
HOT_KEY_ID = 1

WM_HOTKEY = 0x0312

def setClipboardMimeToHTML():
    clipboard = QtGui.QApplication.clipboard()
    mimeData = QtCore.QMimeData()
    mimeData.setText(clipboard.text())
    mimeData.setHtml(clipboard.text())
    clipboard.setMimeData(mimeData) 

def isClipboardEmpty():
    clipboard = QtGui.QApplication.clipboard()
    return (clipboard.text() == "")

def chc2c(syn = '', color = 'default', isLineNumber = False, filename = ''):
    import os
    # ugly but useful vim's format code
    setCBLinkToSystem = '-c "set clipboard+=unnamed"'
    pasteFromCB = ' -c ":norm p" '
    setSyntax = ' -c ":syntax on|:set syn=' + syn + '"'
    setColor = ' -c ":color ' + color + '"'
    setLineNumber = ' -c ":set nu' + ('"' if isLineNumber else '!"')
    toHtml =  ' -c ":TOhtml" '
    copyToCB = '-c ":norm ggVGy" '
    saveToFile =  (' -c ":w ' + filename + '" ') if (filename != '') else ''
    quit = ' -c ":qa!"'
    vimCmd = 'gvim ' +  setCBLinkToSystem + pasteFromCB +  setSyntax + setColor\
            + setLineNumber + toHtml + saveToFile + copyToCB + quit
    os.system(vimCmd)
    
    setClipboardMimeToHTML()
    
    return True    


class ClipboardHighlighter(QtGui.QMainWindow):
    def __init__(self):
        super(ClipboardHighlighter, self).__init__()
        
        self.createActions()
        self.createTrayIcon()
    
    def about(self):
        self.about = AboutDialog()
        self.about.show()
        
    def setSyn(self):
        
        checkedAction = self.synGroup.checkedAction()
        if checkedAction != None:
            self.syn = checkedAction.text()
        else:
            self.syn = ''
        
    def createActions(self):
        self.quitAction = QtGui.QAction("&Quit", self,
                                        triggered=QtGui.qApp.quit)
        
        self.aboutAction = QtGui.QAction("&About", self,
                                        triggered=self.about)
        
        self.synGroup = QtGui.QActionGroup(self)
        
        for syn in config.syntaxSupport:
            action = QtGui.QAction(syn, self, checkable=True,
                triggered=self.setSyn)
            self.synGroup.addAction(action)
            
        actions = self.synGroup.actions()
        
        if len(actions) != 0:
            actions[0].setChecked(True)
        
        self.setSyn()
            
    def createTrayIcon(self):
        if not QtGui.QSystemTrayIcon.isSystemTrayAvailable():
            QtGui.QMessageBox.critical(None, 'Systray', 'System trayIcon is not support by this system')
            sys.exit(1)
            
        self.icon = QtGui.QIcon('jt.png')
        self.trayIconMenu = QtGui.QMenu(self)
        self.trayIconMenu.addActions(self.synGroup.actions())
        
        self.trayIcon = QtGui.QSystemTrayIcon(self)
        self.trayIcon.setContextMenu(self.trayIconMenu)
        self.trayIconMenu.addSeparator()
        
        self.trayIconMenu.addAction(self.aboutAction)
        self.trayIconMenu.addAction(self.quitAction)
        self.trayIcon.setIcon(self.icon)
        self.trayIcon.setVisible(True)
        
class GlobalHotKeyApp(QtGui.QApplication):
    def __init__(self, argv):
        super().__init__(argv)
        
        prototype = WINFUNCTYPE(c_bool, c_int, c_int, UINT, UINT)
        paramflags = (1, 'hWnd', 0), (1, 'id', 0), (1, 'fsModifiers', 0), (1, 'vk', 0)
        self.RegisterHotKey = prototype(('RegisterHotKey', windll.user32), paramflags)
        
    def register(self):
        self.mainWindow = ClipboardHighlighter()
        
        r = self.RegisterHotKey(c_int(self.mainWindow.winId()), HOT_KEY_ID, config.modifier, ord( config.hotkey.upper() ))
        if not r:
            QtGui.QMessageBox.critical(None, 'Hot key', 'Can\'t Register Hotkey Win + Z')
            sys.exit(1)
    
    # these code don't have compatibility with other OS 
    def winEventFilter(self, msg):
        debug_out("Message: " + str(hex(msg.message)) )
        if msg.message == WM_HOTKEY:
            if isClipboardEmpty():
                self.mainWindow.trayIcon.showMessage("failed", "Clipboard is Empty.")
                return True, 0
            debug_out("Got the Hotkey!")
            debug_out(config.filename)
            
            import imp
            imp.reload(config)
            chc2c(self.mainWindow.syn, config.color, config.isLineNumber, config.filename)
            self.mainWindow.trayIcon.showMessage("success", "transformed the data in clipboard to html.")
            return True, 0
        
        return False, 0


    
if __name__ == '__main__':
    app = GlobalHotKeyApp(sys.argv)
    app.register()
     
    QtGui.QApplication.setQuitOnLastWindowClosed(False)
    
    r = app.exec_()
    
    app.mainWindow.trayIcon.setVisible(False)
    sys.exit(r)
    
        

    
